import {utils,tree as Tree} from "../../packages"
import {RouteRecordRaw,RouteRecordNormalized} from "vue-router"
// 路由节点 结构 路由、菜单，
// enum Types {menu="menu",route="route",button="button"}
// 路由菜单节点数据结构
interface NodeIntf extends RouteRecordNormalized  {
  alias?:string | string[];
  component?:string|any;
}

// 动态路由配置项
// 基础路由 常规如登陆，首页，注册，密码找回 等不需要用户登陆的页面 
const baseRoutes:RouteRecordRaw[] = [
  {path: '/',redirect:'/login'},
  //{path: '/home',name: 'Home',component: () => import ('/src/views/base/home.vue')},
  {path:'/login',name:'Login',component:() => import('/src/views/base/login.vue')},
  {path:'/register',name:'Register',component: () => import('/src/views/base/register.vue')},
  {path:'/404',name:'404',component:() => import('/src/views/base/error-404.vue')},
]
// 重定向路由，放在路由表最后 默认进入 404 页面
const finalRoutes:RouteRecordRaw[] = [
  // {path:'/:pathMatch(.*)',redirect:'/404'}
]

// 动态懒加载 路由页面
const loadPage = (p?:string) => p? () => import(`@/${p}.vue`):undefined;
// 创建路由配置项
const RouterConfig = {
  mode:'history',
  base: '',
}
//
const HomePath = ''
const emptyComponent = () => import('/src/components/container/empty.container.vue') // 空容器
const loginPath = '/login'
//
const createMyRoutes = (tree:NodeIntf[] = []) : RouteRecordRaw[] => {
  const rts = createDynamicRoutes(tree);
  return [...baseRoutes,...rts,...finalRoutes]
}
// 动态路由表生成规则 动态路由数据可通过 api 获取
const createDynamicRoutes = (tree:NodeIntf[] = []) : RouteRecordRaw[] => {
  // 定义 路由节点 生成方法
  const keys = 'path,name,redirect,component,meta,alias'.split(',')
  const f:Tree.CallbackAny<NodeIntf> = (n:any,l,i,pn) => {
    // 可在此处更改字段映射
    const {path='',component} = n;
    const bool:boolean = utils.isURL(path)
    if(bool) return undefined;
    const node:any = {}
    keys.forEach(k => {
      if(n[k]){
        node[k] = n[k]
      }
    })
    if(!pn && !/^\//.test(path)){node.path = '/' + path}
    if(component){node.component = loadPage(component)}
    else{node.component = emptyComponent;}
    
    // 返回 undefined 会删除节点
    return node;
  }
  // 利用树工具方法构建路由表
  const routes:RouteRecordRaw[] = Tree.reset(tree,f) || []
  console.log(routes)
  // return [...baseRoutes,...routes,...finalRoutes]
  return routes;
}


export {
  NodeIntf,
  RouterConfig,
  HomePath,
  loginPath,
  createMyRoutes,
  createDynamicRoutes
}